package com.lincoln.Client.context;

import com.lincoln.Client.utils.MusicPlay;

import javax.sound.sampled.*;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SoundContext {
    public static Map<String, File> sounds = new HashMap<>();

    static {
        flashSounds();
    }

    public static void main(String[] args) {
        flashSounds();
    }

    /**
     * 获取声音文件
     *
     * @param name
     * @return
     */
    public static File getSound(String name) {
        return sounds.get(name);
    }

    public static String getSoundPath() {
        return SettingContext.getMainDir() + "/sounds/";
    }

    /**
     * 重新读取声音列表
     */
    public static void flashSounds() {
        sounds = new HashMap<>();
        List<String> list = readAllFile(getSoundPath());
        for (String path : list) {
            File file = new File(path);
            String name = path.substring(path.lastIndexOf("\\") + 1);
            sounds.put(name, file);
        }
    }

    /**
     * 获取声音列表
     *
     * @return
     */
    public static List<String> getSoundList() {
        return new ArrayList<>(sounds.keySet());
    }

    /**
     * 读取文件夹下所有音乐文件
     *
     * @param filepath
     * @return
     */
    public static List<String> readAllFile(String filepath) {
        List<String> list = new ArrayList<>();
        File file = new File(filepath);
        if (!file.isDirectory()) {
            return list;
        } else if (file.isDirectory()) {
            String[] filelist = file.list();
            for (int i = 0; i < filelist.length; i++) {
                if (!(filelist[i].endsWith(".wav") || filelist[i].endsWith(".WAV")) && !(filelist[i].endsWith(".mp3") || filelist[i].endsWith(".MP3"))) {
                    continue;
                }
                File readfile = new File(filepath + "\\" + filelist[i]);
                if (!readfile.isDirectory()) {
                    list.add(readfile.getPath());
                }
            }
            return list;
        }
        return list;
    }

    public static void play(String name) {
        try {
            File sound = getSound(name);
            MusicPlay musicPlay = new MusicPlay(sound);
            musicPlay.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
